package com.gitee.wsl.doc.prosemirror.state.command

import com.gitee.wsl.doc.prosemirror.model.node.ext.canJoin
import com.gitee.wsl.doc.prosemirror.model.node.ext.joinPoint
import com.gitee.wsl.doc.prosemirror.state.Command
import com.gitee.wsl.doc.prosemirror.state.CommandDispatch
import com.gitee.wsl.doc.prosemirror.state.EditorState
import com.gitee.wsl.doc.prosemirror.state.selection.NodeSelection
import com.gitee.wsl.doc.prosemirror.transform.ext.join


object JoinUp: Command {
    override fun exec(
        state: EditorState,
        dispatch: CommandDispatch?,
    ): Boolean {
        val sel = state.selection
        val nodeSel = sel is NodeSelection
        val point:Int?
        if (nodeSel) {
            if (sel.node.isTextblock || !state.doc.canJoin( sel.from)) return false
            point = sel.from
        } else {
            point = state.doc.joinPoint(sel.from, -1)
            if (point == null) return false
        }
        if (dispatch!=null) {
            val tr = state.tr.join(point)
            if (nodeSel) tr.setSelection(NodeSelection.create(tr.doc, point - state.doc.resolve(point).nodeBefore!!.nodeSize))
            dispatch(tr.scrollIntoView())
        }
        return true
    }
}

/// Join the selected block or, if there is a text selection, the
/// closest ancestor block of the selection that can be joined, with
/// the sibling above it.
val Command.Companion.joinUp get() = JoinUp